package start.redisstream;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.Range;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StreamOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@Slf4j
public class DeadMsgScheduleTask {

    @Autowired
    private StringRedisTemplate redisTemplate;

    //@Scheduled(cron = "30 * * * * ?")  //监控未自动ACK消息， 30秒一次
    public void deadRecordListen() {
        StreamOperations<String, String, String> streamOperations = this.redisTemplate.opsForStream();
        // 获取my_group中的pending消息信息，本质上就是执行XPENDING指令
        PendingMessagesSummary pendingMessagesSummary = streamOperations.pending("lzm_stream", "lzm_group");
        // 所有pending消息的数量
        long totalPendingMessages = pendingMessagesSummary.getTotalPendingMessages();
        if (totalPendingMessages == 0) {
            return;
        }
        // 消费组名称
        String groupName = pendingMessagesSummary.getGroupName();
        // pending队列中的最小ID
        String minMessageId = pendingMessagesSummary.minMessageId();
        // pending队列中的最大ID
        String maxMessageId = pendingMessagesSummary.maxMessageId();
        log.info("消费组：{}，一共有{}条pending消息，最大ID={}，最小ID={}", groupName, totalPendingMessages, minMessageId, maxMessageId);
        // 每个消费者的pending消息数量
        Map<String, Long> pendingMessagesPerConsumer = pendingMessagesSummary.getPendingMessagesPerConsumer();
        pendingMessagesPerConsumer.entrySet().forEach(entry -> {
            // 消费者
            String consumer = entry.getKey();
            // 消费者的pending消息数量
            long consumerTotalPendingMessages = entry.getValue();
            log.info("消费者：{}，一共有{}条pending消息", consumer, consumerTotalPendingMessages);
            //read方法能 改 deliveryCount值
            //List<MapRecord<String, String, String>>  retVal = streamOperations.read(Consumer.from("lzm_group", consumer), StreamOffset.create("lzm_stream", ReadOffset.from("0")));
            if (consumerTotalPendingMessages > 0) {
                // 读取消费者pending队列的前10条记录，从ID=0的记录开始，一直到ID最大值
                PendingMessages pendingMessages = streamOperations.pending("lzm_stream", Consumer.from("lzm_group", consumer), Range.closed("0", "+"), consumerTotalPendingMessages);
                // 遍历所有Opending消息的详情
                pendingMessages.forEach(message -> {
                    // 消息的ID
                    RecordId recordId = message.getId();
                    // 消息从消费组中获取，到此刻的时间
                    Duration elapsedTimeSinceLastDelivery = message.getElapsedTimeSinceLastDelivery();
                    // 消息被获取的次数
                    long deliveryCount = message.getTotalDeliveryCount();
                    log.info("pending消息，id={}, elapsedTimeSinceLastDelivery={}, deliveryCount={}", recordId, elapsedTimeSinceLastDelivery, deliveryCount);
                    /**
                     * 演示手动消费的这个判断非常的针对，目的就是要读取消费者“my_consumer1”pending消息中，ID=1668231125078-0的这条消息
                     */
                    String dealId = "1668231125078-0";
                    if (recordId.getValue().equals(dealId)) {
                        //通过streamOperations，直接读取这条pending消息， range只能遍历 不能改deliveryCount值
                        List<MapRecord<String, String, String>> result = streamOperations.range("lzm_stream", Range.closed(dealId, dealId));
                        // 开始和结束都是同一个ID，所以结果只有一条
                        MapRecord<String, String, String> record = result.get(0);
                        /*
                        // 这里执行日志输出，模拟的就是消费逻辑
                        log.info("消费了pending消息：id={}, value={}", record.getId(), record.getValue());
                        //如果手动消费成功后，往消费组提交消息的ACK
                        //Long retVal = streamOperations.acknowledge("lzm_group", record);
                        //log.info("消息ack，一共ack了{}条", retVal);*/
                    }
                });
            }
        });


    }
}

